package net.wanho.controller;

import cn.hutool.core.util.IdUtil;
import lombok.RequiredArgsConstructor;
import net.wanho.util.LockUtil;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Author：汤小洋
 * Date：2023-07-24 10:08
 * Description：<描述>
 */
@RestController
@RequiredArgsConstructor
public class LockController {

    private final StringRedisTemplate redisTemplate;

    /**
     * 下单时减库存
     */
    // @RequestMapping("/deductStock")
    // public String deductStock() {
    //     System.out.println(Thread.currentThread().getName()+"-----------------正在下单");
    //
    //     synchronized (this) {
    //         int total = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
    //         if (total>0){
    //             try {
    //                 Thread.sleep(5000);
    //             } catch (InterruptedException e) {
    //                 throw new RuntimeException(e);
    //             }
    //             total = total - 1;
    //             redisTemplate.opsForValue().set("stock",total+"");
    //             return "下单成功，库存还剩下："+total;
    //         }
    //     }
    //
    //     return "下单失败，库存不足";
    // }

    @RequestMapping("/deductStock")
    public String deductStock() {
        System.out.println(Thread.currentThread().getName()+"-----------------正在下单");

        /**
         * 1.获取锁
         */
        String lockName = "stock_lock";
        String value = IdUtil.simpleUUID();
        if (! LockUtil.getLock(lockName,value)) {
            return "下单失败，获取锁失败";
        }

        int total = Integer.parseInt(redisTemplate.opsForValue().get("stock"));
        if (total>0){
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            total = total - 1;
            redisTemplate.opsForValue().set("stock",total+"");

            /**
             * 2.释放锁
             */
            LockUtil.unlock(lockName,value);
            return "下单成功，库存还剩下："+total;
        }

        return "下单失败，库存不足";
    }




}
